import {
	baseUrl
} from '../config'

export default function getrequest(uri, data = {}, type = 'GET', contentType = 'application/x-www-form-urlencoded') {
	let url = baseUrl + uri
	let header = {
		'Content-Type': contentType
	}
	header = {
		...header,
		token: uni.getStorageSync('token')
	}
	return new Promise(function(reslove, reject) {
		try {
			uni.request({
				url: url,
				// timeout: 3000,
				header: header,
				method: type,
				data: data,
				success: res => {
					res.data = res.data || {};
					res.data.success = res.data.code == 0
					if (res.data.code == 0) {
						if (uri.indexOf('checkLogin') > -1) {
							let xtoken = res.data.data.userId
							uni.setStorageSync('token', xtoken)
						}
						reslove(res.data);
					} else {
						if (res.data.code == 401) {
							uni.removeStorageSync('token')
							uni.showModal({
								title: "提示",
								content: '登录超时,请重新登陆',
								confirmText: '去登陆',
								showCancel: false,
								success(res) {
									if (res.confirm) {
										const pages = getCurrentPages();
										uni.navigateTo({
											url: '/pages/login/login?url=' + encodeURIComponent('/' + pages[pages.length - 1].route)
										})
									}
								}
							});
						} else {
							//console.error(res.data.msg)
							// uni.showModal({
							// 	content: res.data.msg,
							// 	showCancel: false
							// });
						}
						reslove(res.data)
					}
				},
				fail: (err) => {
					reslove({
						success: false,
						msg: err.errMsg
					})
				}
			});
		} 
		catch (err) {
			reslove({
				success: false,
				msg: err
			})
		}
	})
}